Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

264
Views
[JavaScript]Add elements to a global array in a function and keep them

window.onload = function(){
    func1();
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}

console.log(list);

Which the output log is an empty array, then how do I add elements to a global array in a function, and access them globally?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Your function's code is fine.

However, you are logging the array using console.log before func1() gets to run, since window.onload fires AFTER everything has loaded.

about 4 years ago · Juan Pablo Isaza Report

0

Let's focus on why the console.log in the end is empty.

Note that :

window. onload() is invoked when all resources (the document, objects, images, css, etc) have finished rendering.

So after the console output the list value, if will execute the func1 and assign the value to list, but before that list is just an empty array.

If could see the following snippet, if you put the console to the window.onload function, it works as epected.

You could use push to add item to array and use index to access a specific element.

window.onload = function(){
    func1();
    console.log(list);
    func2()
    console.log(list)
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}
console.log(list);
function func2(){
list[0] =9999

}

about 4 years ago · Juan Pablo Isaza Report

0

You need to wait for the window to load and call your function func1 before logging the value of the array to console...

window.onload = function(){
    func1();
    console.log(list);
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!